<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
// import { appStockQuery } from "@/services/goods";

// import { stockCounterStore } from "@/stores/stock";

import { UnpackProduct } from "@/services/unpacking.js";
import { useGoodStore } from "@/stores/goods.js";

const goods = useGoodStore();

// const stockObj = stockCounterStore();
const keyword = ref("");

// import tabbarView from "../components/tabbar.vue";
const code = ref("");
//获取商品
const form = ref({
  pageIndex: 1,
  pageSize: 20,
  keyword: "",
});

onLoad((option) => {
  if (option.code) {
    code.value = option.code ? option.code : "";
  }
  if (option.code) {
    form.value.keyword = option.code ? option.code : "";
  }

  if (uni.getStorageSync("goodsSel")) {
    selectNumList.value = JSON.parse(uni.getStorageSync("goodsSel"));
  }

  // if (uni.getStorageSync("shopselect")) {
  //   selectShopObj.value = JSON.parse(uni.getStorageSync("shopselect"));
  // }
});

const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getappStockQuery(1);
};
const isShowBtn = ref(true);
const searchFun = () => {
  getappStockQuery(1);
};
const focusFun = () => {
  isShowBtn.value = false;
};
const blurFun = () => {
  isShowBtn.value = true;
};

onReachBottom(() => {
  console.log("触底了");
  getappStockQuery();
});
onMounted(() => {
  getappStockQuery();
});

const goodsNum = ref(0);
const payPrice = ref(0);

const productData = ref([]);

const loading = ref("");
const getappStockQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
    loading.value = "";
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    let res = await UnpackProduct(form.value);
    if (res.code == 200) {
      // res.data.datas.forEach((element) => {
      //   let ifHave = false;
      //   selectNumList.value.forEach((item) => {
      //     if (element.id == item.id) {
      //       ifHave = true;
      //       element.select = item.select;
      //     }
      //   });
      //   if (!ifHave) {
      //     element.transferNum = 0;
      //   }
      // });
      productData.value = productData.value.concat(res.data ? res.data : []);
      console.log(productData.value);
      form.value.pageIndex = form.value.pageIndex + 1;

      // if (res.data.datas.length < form.value.pageSize) {
      //   loading.value = "noMore";
      // } else {
      //   loading.value = "More";
      // }
      loading.value = "noMore";
    } else {
    }

    console.log(res);
  } catch (e) {}
};
function getNum() {
  let num = 0;
  selectNumList.value.forEach((item) => {
    num += item.transferNum;
    console.log(item.transferNum, "num");
  });
  goodsNum.value = num;
}
const selectNumList = ref([]);
const selectItem = ref({});
const showMode = ref(false);
const showIndex = ref(0);
const showTwoIndex = ref(0);
const onClickMinus = (item, index) => {
  if (item.stockNum <= 0) {
    uni.showToast({
      title: "库存不足",
      icon: "none",
    });
    return;
  }
  selectItem.value = item;
  showIndex.value = index;

  showTwoIndex.value = selectNumList.value.length;
  item.transferNum = item.transferNum + 1;
  if (item.transferNum > item.stockNum) {
    showMode.value = true;
  }

  if (selectNumList.value <= 0) {
    selectNumList.value.push(item);
    getNum();
    return;
  }
  let isnew = true;
  selectNumList.value.forEach((item1, index1) => {
    if (item1.id == item.id) {
      isnew = false;
      selectNumList.value[index1] = item;
    }
  });
  if (isnew) {
    selectNumList.value.push(item);
  }
  getNum();

  // selectNumList.value = [...selectNumList.value, ...[item]];
};
const valChange = (item, index, e) => {
  selectItem.value = item;
  showIndex.value = index;

  if (e.value > item.stockNum) {
    showMode.value = true;
  }

  if (selectNumList.value <= 0) {
    selectNumList.value.push(item);
    getNum();
    return;
  }
  let isnew = true;
  selectNumList.value.forEach((item1, index1) => {
    if (item1.id == item.id) {
      showTwoIndex.value = index1;
      selectNumList.value[index1] = item;
      isnew = false;
    }
  });
  if (isnew) {
    showTwoIndex.value = selectNumList.value.length;
    selectNumList.value.push(item);
  }
  console.log(selectNumList.value, "sadas");
  setTimeout(() => {
    selectNumList.value.forEach((item, index) => {
      if (item.transferNum <= 0) {
        selectNumList.value.splice(index, 1);
      }
    });
    getNum();
  }, 100);
};

const blurChange = (item, index, e) => {
  if (e.value == "") {
    item.transferNum = 0;
  }
};

//编辑商品
const goEdt = (item) => {
  uni.navigateTo({ url: "/pages/goods/goods_add/index?id=" + item.id });
};

const cancelFun = () => {
  showMode.value = false;
  productData.value[showIndex.value].transferNum =
    productData.value[showIndex.value].stockNum;

  selectNumList.value[showTwoIndex.value].transferNum =
    selectNumList.value[showTwoIndex.value].stockNum;

  getNum();
};
const confirmFun = () => {
  showMode.value = false;
};
//改价列表
const goRecord = () => {
  // selectNumList.value.forEach((item, index) => {
  //   if (item.transferNum <= 0) {
  //     selectNumList.value.splice(index, 1);
  //   }
  // });
  if (selectNumList.value.length <= 0) {
    uni.showToast({
      title: "请先选择商品",
      icon: "none",
    });
    return;
  }

  uni.setStorageSync("goodsSel", JSON.stringify(selectNumList.value));

  uni.redirectTo({
    url: "/pages/stocktaking/cerate/index",
  });
};

const onClickItem = (item, index) => {
  // uni.setStorageSync("goods", JSON.stringify(selectNumList.value));

  goods.setGood(item);
  var pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.redirectTo({
      url: "/pages/unpacking/add/index?type=1",
    });
  }
};

//无网状态
const connected = () => {
  getappStockQuery();
};
</script>

<template>
  <topNav :title="'选择拆包商品'" @save="saveFun" rType="save"></topNav>
  <view
    class="top"
    style="padding-bottom: 20rpx"
    :class="!openDropdown ? 'top-open' : ''"
    :style="'top: calc( 88rpx + ' + topHeight + 'px);'"
  >
    <view class="search-k">
      <up-search
        placeholder="商品编号/商品名称"
        v-model="form.keyword"
        :showAction="false"
        @search="searchFun"
      ></up-search>
    </view>
  </view>

  <view class="goods_form">
    <view
      class="scroll-Y-item"
      @click.stop="onClickItem(item, index)"
      v-for="(item, index) in productData"
      :key="index"
    >
      <view class="scroll-item-left">
        <image :src="item.image ? item.image : ''" mode="scaleToFill" />
      </view>
      <view class="scroll-item-right">
        <view class="goods-item-title"> {{ item.name }} </view>
        <!-- <view class="goods-item-spec">
          条形码: {{ item.barCode ? item.barCode : "--" }}
        </view> -->
        <view class="goods-item-spec" v-if="!item.dhCode">
          商品码:{{ item.barCode ? item.barCode : "" }}</view
        >
        <!-- <view class="goods-item-spec" v-if="item.dhCode">
          称码:{{ item.dhCode ? item.dhCode : "" }}</view
        > -->
        <!-- <view class="goods-item-price">
          ¥{{ item.salePrice ? item.salePrice : 0.0 }}
          {{ item.unit ? "/" + item.unit : "" }}
          <text class="goods-item-spec">库存:</text>
          {{ item.stockNum || 0 }}
        </view> -->
      </view>
      <view class="goods-item-num">
        <up-icon name="arrow-right" color="#86909c" size="35rpx"></up-icon>
        <!-- <view class="goods-item-num-item" :class="item.select ? 'active' : ''">
          
          <image
            v-if="item.select"
            src="@/static/images/select.png"
            mode="scaleToFill"
          />
        </view> -->
      </view>
    </view>
  </view>
  <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
    <view class="noData-img">
      <image src="@/static/nodate/datas.png" mode="scaleToFill" />
      <view>暂无可拆包商品 </view>
    </view>
  </view>
  <view class="loading-form" v-if="loading && productData.length > 0"
    ><van-loading size="24rpx" v-if="loading == 'Loading'"
      ><text class="loading-text">加载中...</text>
    </van-loading>
    <text class="loading-text" v-if="loading == 'More'">加载更多</text>
    <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
  </view>

  <view style="height: 100rpx; width: 100%"></view>

  <!-- <view class="goods_bt" v-if="isShowBtn">
    <view class="goods_bt_to">
      <text>共{{ selectNumList.length }}款</text>
      <van-button class="val-button" type="primary" @click="goRecord"
        >确认</van-button
      >
    </view>
  </view> -->

  <up-modal
    :show="showMode"
    :title="
      selectItem.name +
      ', 库存超出' +
      (selectItem.stockNum - selectItem.transferNum)
    "
    width="500rpx"
    :content="''"
    @cancel="cancelFun"
    @confirm="confirmFun"
    confirmText="仍然调货"
    cancelText="取消"
    :showCancelButton="true"
  ></up-modal>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
